package com.freight.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.freight.common.core.utils.StringUtils;
import com.freight.common.redis.service.RedisService;
import com.freight.system.domain.QiniuResult;
import com.freight.system.service.ISysConfigService;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class QiniuService {

   // private static final Logger log = LoggerFactory.getLogger(CommonController.class);
    private static final String UPLOAD_TOKEN_KEY="qiniu:uploadToken";
    private static final String DOWNLOAD_TOKEN_KEY="qiniu:uploadToken";
    @Autowired
    ISysConfigService sysConfigService;
    @Autowired
    RedisService redisService;
    private String ACCESS_KEY="";
    private String SECRET_KEY="";
    private String BUCKET="";
    private String DOMAIN="";

    public void init(){
        this.ACCESS_KEY=sysConfigService.selectConfigByKey("qiniu.ak");
        this.SECRET_KEY=sysConfigService.selectConfigByKey("qiniu.sk");
        this.BUCKET=sysConfigService.selectConfigByKey("qiniu.bucket");
        this.DOMAIN=sysConfigService.selectConfigByKey("qiniu.domain");
    }

    /***
     * 获取七牛云上传凭证
     * @return
     */
    public String getUploadToken(){
        this.init();
        //获取相应设置，获取上传token
        if(redisService.getCacheObject(UPLOAD_TOKEN_KEY)==null) {
            String upToken=this.getToken(ACCESS_KEY,SECRET_KEY,BUCKET,DOMAIN);
            if (!StringUtils.isEmpty(upToken)) {
                redisService.setCacheObject(UPLOAD_TOKEN_KEY, upToken, 3000l, TimeUnit.SECONDS);
                return upToken;
            }else{
                return null;
            }
        }else{
            return redisService.getCacheObject(UPLOAD_TOKEN_KEY);
        }
    }

    /**
     *
     * @param accessKey
     * @param secretKey
     * @param bucket
     * @param domain
     * @return
     */
    private String getToken(String accessKey,String secretKey,String bucket,String domain){
        Auth auth = Auth.create(accessKey, secretKey);
        StringMap putPolicy = new StringMap();
        //设置返回格式
        putPolicy.put("returnBody", "{\"fileUrl\": \"" + domain + "$(key)\",\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"fsize\":$(fsize)}\"}");//上传成功后返回的json
        long expireSeconds = 3600;//过期时间
        String upToken = auth.uploadToken(bucket, null, expireSeconds, putPolicy);
        return upToken;
    }

    /**
     * 服务器
     * @param multipartFile
     * @param key
     * @return
     */
    public QiniuResult upload(MultipartFile multipartFile, String key){
        //创建上传对象
        Configuration cfg = new Configuration(Region.huanan());
        cfg.useHttpsDomains = false;
        UploadManager uploadManager = new UploadManager(cfg);
        try {
            FileInputStream inputStream=(FileInputStream)multipartFile.getInputStream();
            byte[] uploadBytes = new byte[inputStream.available()];
            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
            //调用put方法上传
            Response res = uploadManager.put(byteInputStream,key,this.getUploadToken(),null, null);
            //解析上传成功的结果
            QiniuResult result=JSONObject.parseObject(res.bodyString(),QiniuResult.class);
            System.out.println("#######"+res.bodyString());
            return result;
        } catch (QiniuException e) {
            e.printStackTrace();
            return null;
        }catch (IOException e){
            e.printStackTrace();
            return null;
        }
    }

}
